package com.bigdata.appliance.handler;

import com.bigdata.appliance.common.exception.BusinessException;
import com.bigdata.appliance.common.exception.ResponseCode;
import com.bigdata.appliance.common.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class RestResponseExceptionHandler {
    /**
     * 异常监控
     */
    @ExceptionHandler(Exception.class)
    public <T> DataResult<T> exception(Exception e) {
        log.error("arithmeticException:{}", e);
        return DataResult.fail(ResponseCode.SYSTEM_ERROR.getCode(), ResponseCode.SYSTEM_ERROR.getMessage());
    }

    /**
     * 自定义业务异常处理
     */
    @ExceptionHandler(BusinessException.class)
    public <T> DataResult<T> exception(BusinessException e) {
        log.error("BusinessException:{}", e);
        return DataResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 参数校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public <T> DataResult<T> exception(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:{}", e);
        String message = e.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(","));
        return DataResult.fail(ResponseCode.DATA_PARAM_ERROR.getCode(), message);
    }

}
